<template>
	<div class="modal-custom-base-wrap">
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="" />
		</el-dialog>


		<el-dialog :title="modalTitle" width="1000px" custom-class="modal-custom-base" :close-on-click-modal="false"
			:close-on-press-escape="false" :visible.sync="show" :append-to-body="true" @close="handleClose()"
			@closed="handleClosed()">
			<div class="modal-ctx" data-type="基础表单弹窗">
				<div class="input-items" v-if="formColumns.length">
					<div class="input-item" v-for="(item, index) in formColumns" :key="index"
						:style="item.width ? { width: item.width + '%' } : {}" :class="{ 'hidden-item': item.hidden }">
						<div class="input-box" :class="item.col">
							<div class="label" :class="{ required: item.is_required }">
								{{ item.label }}
							</div>
							<div class="val" :data-type="item.type">
								<div class="form-ele">
									<!-- 单行文本 -->
									<el-input v-if="item.type == 'input' || item.type == 'number' || !item.type"
										:type="item.type == 'number' ? 'number' : 'text'" :disabled="item.disabled"
										v-model="form[item.col]" :placeholder="'请输入' + item.label">
										<template v-if="item.append" slot="append">{{ item.append }}</template>
									</el-input>

									<!-- 多行文本 -->
									<el-input v-else-if="item.type == 'textarea'" :disabled="item.disabled"
										v-model="form[item.col]" type="textarea"
										:placeholder="item.placeholder || '请输入' + item.label"
										:autosize="item.autosize"></el-input>

									<!-- 选项 -->
									<formSelect v-else-if="item.type == 'select'" :form="form" :item="item"
										ref="formSelect" />
									<!-- <el-select
                      v-else-if="item.type == 'select'"
                      :disabled="item.disabled"
                      v-model="form[item.col]"
                      :placeholder="'请选择' + item.label"
                    >
                      <el-option
                        v-for="(item, index) in item.option"
                        :key="index"
                        :label="item.label"
                        :value="item.label"
                      ></el-option>
                    </el-select> -->

									<el-radio-group v-else-if="item.type == 'radio'" v-model="form[item.col]">
										<el-radio v-for="(sub, sindex) in item.options" :key="sindex"
											:label="sub[item.valueKey]">{{
												sub[item.labelKey]
											}}</el-radio>
									</el-radio-group>

									<el-date-picker v-else-if="item.type == 'date'" :disabled="item.disabled"
										v-model="form[item.col]" :picker-options="item['picker-options'] || {}"
										type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>

									<el-date-picker v-else-if="item.type == 'daterange'" :disabled="item.disabled"
										v-model="form[item.col]" type="daterange" value-format="yyyy-MM-dd"
										range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
									</el-date-picker>

									<el-date-picker v-else-if="item.type == 'dateTimePicker'" :disabled="item.disabled"
										v-model="form[item.col]" type="daterange" value-format="yyyy-MM-dd"
										range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
									</el-date-picker>

									<el-date-picker v-else-if="item.type == 'datetime'" v-model="form[item.col]"
										type="datetime" :placeholder="item.placeholder || '请选择' + item.label"
										:picker-options="datetimePickerOptions" value-format="yyyy-MM-dd HH:mm:ss">
									</el-date-picker>

									<!-- 时间选择 -->
									<!-- <el-time-picker
                      v-else-if="item.type == 'time'"
                      :disabled="item.disabled"
                      value-format="HH:ss"
                      v-model="form[item.col]"
                      placeholder="请选择时间"
                    >
                    </el-time-picker> -->

									<div type="图片上传" class="image-upload-box" v-else-if="item.type == 'upload-image'">
										<el-upload class="upload-image" list-type="picture-card" accept="image/*"
											:multiple="item.upload_multiple" :limit="item.upload_limit"
											:name="upload_col_name" :action="mix_upload_action"
											:data="upload_other_data" :file-list="cacheMap[item.cache_key]"
											:http-request="(uploadInfo) => handle_upload_image_request(uploadInfo, item)
												" :on-success="handle_upload_image_success" :on-remove="(file, fileList) =>
							handle_upload_image_remove({ file, fileList, formItem: item })
							" :before-upload="handle_upload_image_before" :on-preview="handlePictureCardPreview">
											<i class="el-icon-plus" v-if="item.upload_limit"> </i>
											<div class="el-upload__tip" slot="tip" v-if="item.upload_tip">
												{{ item.upload_tip || "" }}
											</div>
										</el-upload>
									</div>

									<div type="视频上传" class="video-upload-box" v-else-if="item.type == 'upload-video'">
										<el-upload class="upload-video" list-type="text" accept="video/*"
											:multiple="item.upload_multiple" :limit="item.upload_limit"
											:name="upload_col_name" :action="mix_upload_action"
											:data="upload_other_data" :file-list="cacheMap[item.cache_key]"
											:http-request="(uploadInfo) => handle_upload_video_request(uploadInfo, item)
												" :on-success="handle_upload_video_success" :on-remove="(file, fileList) =>
							handle_upload_video_remove({ file, fileList, formItem: item })
							" :before-upload="handle_upload_video_before">
											<i class="el-icon-plus" v-if="item.upload_limit"> </i>
										</el-upload>

										<div class="video-preview-box">
											<el-button type="primary" @click="videoPreview(item)">
												预览视频
											</el-button>
										</div>
									</div>

									<div type="选项卡" class="tab-card-box" v-else-if="item.type == 'topic-card'">
										<div class="table-sec">
											<el-table :data="item.tabCardData" stripe border>
												<template v-for="(item, index) in item.tabCardColumns">
													<el-table-column :key="index + item.prop" :prop="item.prop"
														:label="item.label" :width="item.width">
														<template slot-scope="scope">
															<div class="id-text">
																<el-input v-model="scope.row[item.prop]"> </el-input>
															</div>
														</template>
													</el-table-column>
												</template>

												<el-table-column fixed="right" label="操作" width="80">
													<template slot-scope="scope">
														<div data-title="列表操作" class="row-actions-box">
															<el-button @click="tabCardRowDelete(scope.row, scope)"
																type="text">删除</el-button>
														</div>
													</template>
												</el-table-column>
											</el-table>

											<div class="loop-add">
												<el-button type="primary" @click="tabCardAddItem(item)">
													增加
												</el-button>
											</div>
										</div>
									</div>

									<div type="标签列表" class="tag-list-box" v-else-if="item.type == 'tag-list'">
										<el-tag size="small" :key="tag" v-for="tag in tagList" closable
											:disable-transitions="false" @close="tagClose(tag)">
											{{ tag }}
										</el-tag>
										<el-input class="input-new-tag" v-if="tagInputVisible" v-model="tagInputValue"
											ref="tagInputRef" size="small" @keyup.enter.native="tagInputConfirm()"
											@blur="tagInputConfirm()">
										</el-input>
										<el-button v-else class="button-new-tag" size="small" @click="tagShowInput()">+
											添加</el-button>
									</div>

									<div v-else-if="item.type == 'cascader'" type="级联选择" class="cascader-box">
										<el-cascader :options="cascaderOptions" :props="{ checkStrictly: true }"
											clearable></el-cascader>
									</div>

									<div v-else-if="item.type == 'treeSelect'" type="分类树选择" tip="适用于树形分类选择"
										class="tree-box">
										<el-popover ref="popoverTree" placement="top-start" title=""
											:width="treePopWidth" trigger="click" content="">
											<div slot="reference" class="tree-click-box">
												<el-input readonly v-model="treeSelectTitle"
													:placeholder="'请选择' + item.label">
												</el-input>
												<!-- <el-button type="primary"> 选择分类 </el-button> -->
											</div>

											<div class="pop-tree">
												<el-tree :data="item.treeConfig && item.treeConfig.treeData"
													:props="treeProps" :show-checkbox="treeShowCheckbox"
													:node-key="treeNodeKey" :default-expand-all="defaultExpandAll"
													:expand-on-click-node="false" :highlight-current="true" @node-click="(obj, node, self) => treeNodeClick(obj, node, self, item)
													">
												</el-tree>
											</div>
										</el-popover>
									</div>

									<div class="editor-box" v-else-if="item.type == 'rich-editor'">
										<!-- <vue-tinymce v-model="form[item.col]" :setting="richEditorConfig" /> -->
										<tinyRichEditor :id="'tiny-' + item.col" v-model="form[item.col]"
											:ref="'tinyRichEditor-' + item.col" />
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<!-- <el-button @click="testRichEditor()">富文本内容</el-button> -->
				<el-button @click="show = false">取 消</el-button>
				<el-button type="primary" :disabled="isDisabled" @click="formSubmit()">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
// import shengshiqu from "@/components/address/shengshiqu.vue"; //新增地址
import formSelect from "@/components/form/formSelect.vue";

import tinyRichEditor from "@/components/tinyRichEditor.vue";

import {
	mapState
} from "vuex";

export default {
	name: "modal-content-base",
	components: {
		// shengshiqu,
		formSelect,

		tinyRichEditor,
	},
	props: {
		upload_file_list: {
			type: Array,
			default: function () {
				return [];
			},
			required: false,
		},
	},
	data() {
		return {
			isDisabled: false, //按钮禁用
			mode: "", // 增 || 改
			customModalTitle: "", //自定义模态框名称  比如 新闻资讯列表展示 设置热搜 弹窗标题
			customFormData: {},
			idKey: "",
			otherSaveData: {},
			formColumns: [
				//参数来源于页面配置
				// { is_required: 1, col: "channelName", label: "标题",  },
			],
			apiConfig: {
				//参数来源于页面配置
				// idKey: "channelId",
				// list: { method: "get", url: "/app/system/newsChannel/list" },
				// add: {
				//   method: "get",
				//   url: "/app/system/newsChannel",
				//
				// },
				// delete: { method: "delete", url: "/app/system/newsChannel/{channelId}" },
				// edit: { method: "put", url: "/app/system/newsChannel" },
				// detail: { method: "get", url: "/app/system/newsChannel/{channelId}" },
			},
			form: {
				//由 formColumns 生成接口
				//key: ''
			},

			cacheMap: {
				//图片上传类型用来回显数据使用
				key: "",
			},
			datetimePickerOptions: {
				disabledDate(time) {
					return time.getTime() < Date.now();
				},
			},

			// 上传
			upload_col_name: "file",
			upload_other_data: {},
			upload_action: '/upload-url',
			dialogImageUrl: "",
			dialogVisible: false,
			// 上传

			show: false,
			richEditorConfig: {},
			tinyIdList: [],

			// 标签
			tagList: [],
			tagInputVisible: false,
			tagInputValue: "",
			tagInputRef: "tagInputRef",
			// 标签

			// 级联选择
			cascaderOptions: [],
			// 级联选择

			// 树形选择
			treeData: [],
			treeProps: {
				label: "label",
				children: "children",
			},
			treeShowCheckbox: false,
			treeNodeKey: "value",
			defaultExpandAll: true,
			treePopWidth: "",
			treeSelectTitle: "",
			// 树形选择
		};
	},
	computed: {
		modalTitle() {
			let modeModeMap = {
				add: "新增",
				edit: "编辑",
			};
			let action = modeModeMap[this.mode];
			let title = "";

			if (this.customModalTitle) {
				title = this.customModalTitle;
			} else {
				if (this.vuex_iframe_page_data.show) {
					title = action + this.vuex_iframe_page_data.option.modalTitle;
				} else {
					title = action + this.$route.meta.title;
				}
			}

			return title;
		},
	},
	watch: {
		show(val) {
			if (!val) {
				// this.clearInfo();
			} else {
				this.$nextTick(() => {
					var $popBox = document.querySelector(
						'.modal-custom-base [data-type="treeSelect"]'
					);
					if ($popBox) {
						this.treePopWidth = $popBox.getBoundingClientRect().width;
					}
				});
			}
		},
	},
	created() { },
	mounted() { },
	methods: {
		clearInfo() {
			for (var key in this.form) {
				this.form[key] = "";
			}

			this.mode = "";
			this.customModalTitle = "";
			this.customFormData = {};
			this.idKey = "";
			this.otherSaveData = {};
			this.formColumns = [];

			//标签
			this.tagList = [];
			this.tagInputVisible = false;
			this.tagInputValue = "";

			// 分类树
			this.treeSelectTitle = "";

			// 富文本
			// this.clearRichEditor();
		},

		clearRichEditor() {
			//
			// this.tinyIdList.forEach((tinyId) => {
			//   console.warn("销毁", tinyId);

			//   this.$nextTick(() => {
			//     if (tinyMCE.editors[tinyId]) {
			//       tinyMCE.editors[tinyId].destroy();
			//     }
			//   });
			// });
		},

		async init(option) {
			console.warn(
				"vuex => vuex_iframe_page_data",
				JSON.parse(JSON.stringify(this.vuex_iframe_page_data))
			);

			console.warn("初始参数 [option]", JSON.parse(JSON.stringify(option)));
			option = JSON.parse(JSON.stringify(option));
			let {
				//
				mode, //操作模式 新增 || 编辑
				customModalTitle, //自定义模态框名称  比如 新闻资讯列表展示 设置热搜 弹窗标题
				customFormData, //自定义模态框保存时要提交的其他数据  比如 新闻资讯列表展示 设置热搜时需要传递的当前新闻id
				idKey, //id对应字段
				formColumns, //接口表单字段
				apiConfig, //接口列表
				data, //数据行信息 => 编辑时用于回显
				otherSaveData, //保存时需要的其他参数值
			} = option;

			this.mode = mode || "";
			this.customModalTitle = customModalTitle || "";
			this.customFormData = customFormData;
			this.idKey = idKey || "";
			this.otherSaveData = otherSaveData || {};

			let hiddenFormData = {};
			if (this.vuex_iframe_page_data.show && this.vuex_iframe_page_data.option) {
				let {
					hiddenColumnsForAdd
				} = this.vuex_iframe_page_data.option;
				if (hiddenColumnsForAdd && hiddenColumnsForAdd.length) {
					formColumns.forEach((v) => {
						let has_hidden_this = hiddenColumnsForAdd.find(
							(hiddenItem) => hiddenItem.col == v.col
						);
						if (has_hidden_this) {
							v.hidden = true; //隐藏当前项目
							hiddenFormData[has_hidden_this.col] = has_hidden_this.val;
						}
					});
				}
			} else if (option.hiddenFormData) {
				// formColumns
				//
			}

			this.formColumns = formColumns;
			this.apiConfig = apiConfig;
			this.show = true;

			let res_detail = null;
			if (mode == "edit") {
				let apiConfigItem = this.apiConfig.detail;

				//查看详情接口
				res_detail = await this.$api({
					url: apiConfigItem.url,
					method: apiConfigItem.method,
					data: {
						// ...this.form,
					},
					idInfo: {
						idKey: this.idKey,
						idVal: data[this.idKey],
					},
				});
				if (res_detail.code == 200) {
					data = res_detail.data;
				}
				console.warn("详情 res", res_detail);
			}

			let form = {};
			formColumns.forEach((v) => {
				let key = v.col;
				let val = "";
				if (data) {
					val = data[key];
					form[key] = val;
				} else {
					form[key] = "";
				}

				if (v.type == "upload-image") {
					//回显图片上传组件
					this.cacheMap[v.cache_key] = [];
					if (val) {
						//回显数据
						if (v.saveFormat == "jsonObjectArray") {
							try {
								this.cacheMap[v.cache_key] = JSON.parse(val);
								form[key] = JSON.parse(val);
							} catch (error) {
								this.cacheMap[v.cache_key] = [];
								form[key] = [];
							}
						} else if (v.saveFormat == "jsonStringArray") {
							let imageUrlList = val.split(",").filter((v) => v);
							this.cacheMap[v.cache_key] = imageUrlList.map((url) => ({
								name: url,
								url: url,
							}));
							form[key] = val;
						} else {
							this.cacheMap[v.cache_key] = [{
								name: val,
								url: val
							}];

							// form[key] = [{ name: val, url: val }];
							form[key] = val;
						}
					}
				} else if (v.scene == "money") {
					// debugger;
					if (+form[key]) {
						form[key] = form[key] / 100;
					}
				}
			});

			// 回显 => 特殊处理富文本编辑器
			// let rich_editor_item = formColumns.find((v) => v.type == "rich-editor");
			// if (rich_editor_item) {
			//   this.init_rich_editor(rich_editor_item, form[rich_editor_item.col]);
			// }

			//【话题标签卡】
			let topicCardItem = formColumns.find((v) => v.type == "topic-card");
			if (topicCardItem) {
				if (form[topicCardItem.col]) {
					//回显
					try {
						// let array_tab = JSON.parse(form[topicCardItem.col])
						// let tabCardData = []
						// array_tab.forEach(v => {

						// });
						topicCardItem.tabCardData = JSON.parse(form[topicCardItem.col]);
					} catch (error) { }
				}

				let cardData = "";
				if (topicCardItem.tabCardData && topicCardItem.tabCardData.length) {
					cardData = JSON.stringify(topicCardItem.tabCardData);
				} else {
					if (topicCardItem.is_required) {
						let msg = "请完善" + topicCardItem.label + "信息";
						alertErr(msg);
						return;
					}
				}
				this.form[topicCardItem.col] = cardData;
			}
			//【话题标签卡】

			//【标签】关键词
			let tagItem = formColumns.find((v) => v.type == "tag-list");
			if (tagItem) {
				if (form[tagItem.col]) {
					try {
						this.tagList = JSON.parse(form[tagItem.col]);
					} catch (error) { }
				}
			}
			//【标签】关键词

			//【分类树选择】
			let treeItem = formColumns.find((v) => v.type == "treeSelect");
			if (treeItem) {
				// if (form[treeItem.col]) {
				try {
					console.warn("回显父级分类", treeItem.treeConfig.treeFlat);
					// 0 为顶级分类
					let treeNode = treeItem.treeConfig.treeFlat.find(
						(v) => v.value == form[treeItem.col]
					);
					if (treeNode) {
						this.treeSelectTitle = treeNode.label;
					}
				} catch (error) { }
				// }
			}
			//【分类树选择】

			if (data) {
				//编辑表单
				if (idKey) {
					form[idKey] = data[idKey];
				}
			}

			this.form = {
				...form,
				...hiddenFormData,
			};
			console.warn("表单回显 [form]", {
				...this.form
			});
		},

		init_rich_editor(item, richContent) {
			console.warn("初始化富文本编辑器", richContent);
			// let that = this;

			// var tinyId = item.type + "-" + item.col;
			// this.tinyIdList.push(tinyId);

			// this.richEditorConfig = {
			//   selector: "#" + tinyId,
			//   // menubar: false,
			//   menubar: true,
			//   toolbar:
			//     "undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
			//   toolbar_drawer: "sliding",
			//   quickbars_selection_toolbar:
			//     "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",

			//   plugins: "link image media table lists fullscreen quickbars",
			//   language: "zh_CN", //本地化设置
			//   height: 600,
			//   toolbar_mode: "wrap",

			//   fontsize_formats:
			//     "12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 26px 28px 30px 32px 34px 36px",

			//   // images_upload_url: "/api/upload",
			//   // images_upload_base_path: this.imgRoot, //如果返回的地址是相对路径，还有一个参数images_upload_base_path，可以给相对路径指定它所相对的基本路径。

			//   images_upload_handler: (blobInfo, success, failure) => {
			//     const formData = new FormData();
			//     let file = blobInfo.blob();
			//     formData.append("file", file);

			//     console.log("图片上传处理 blobInfo", file);
			//     that.$apiUploadImage(formData).then((res) => {
			//       console.log("图片上传res", res);

			//       if (res.code == 200) {
			//         let name = res.data.name;
			//         let url = res.data.url;
			//         success(url);
			//       }
			//     });
			//   },
			// };

			// this.initTinyContent({
			//   tinyId: tinyId,
			//   richEditorConfig: this.richEditorConfig,
			//   richContent: richContent,
			// });
		},

		// initTinyContent(option) {
		//   console.log("初始化富文本编辑器", option);

		//   let { tinyId, richContent, richEditorConfig } = option;
		//   var $selector = document.querySelector("#" + tinyId);
		//   if ($selector) {
		//     this.$nextTick(() => {
		//       tinymce.init(this.richEditorConfig);
		//       setTimeout(() => {
		//         tinyMCE.editors[tinyId].setContent(richContent);
		//       }, 100);
		//     });
		//   } else {
		//     setTimeout(() => {
		//       this.initTinyContent(option);
		//     }, 100);
		//   }
		// },




		//       :before-close="handleBeforeClose()"
		handleBeforeClose() {
			console.warn("0 handleBeforeClose");
			// this.show = false;
			// setTimeout(() => {
			//   this.clearInfo();
			// }, 0);
		},
		handleClose() {
			console.warn("1 handleClose");
		},
		handleClosed() {
			console.warn("2 handleClosed");
			this.clearInfo();
		},



		formSubmit() {
			//特殊处理话题【页签】类型数据
			let topicCardItem = this.formColumns.find((v) => v.type == "topic-card");
			if (topicCardItem) {
				let cardData = "";
				if (topicCardItem.tabCardData && topicCardItem.tabCardData.length) {
					cardData = JSON.stringify(topicCardItem.tabCardData);
				} else {
					if (topicCardItem.is_required) {
						let msg = "请完善" + topicCardItem.label + "信息";
						alertErr(msg);
						return;
					}
				}
				this.form[topicCardItem.col] = cardData;
			}
			//处理【标签】 eg 产品分类的关键词 keywords: ['词1'，'词2']
			let tagItem = this.formColumns.find((v) => v.type == "tag-list");
			if (tagItem) {
				this.form[tagItem.col] = JSON.stringify(this.tagList);
			}
			console.log("表单提交 form", {
				...this.form
			});

			// let reg_phone = /^1[3-9]\d{9}$/;
			// let reg_email = /^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
			// let is_true_phone = reg_phone.test(this.form.phone);
			// let is_true_email = reg_email.test(this.form.email);

			// 测试使用
			// this.form["carouselImg"] =
			//   "http://s3.tintan.com.cn:3443/solution/solz8t55BguCB0I/vH3NND57LXwJhiMpJB9GWJ.jpg";

			let has_required_but_empty = false;
			let empty_item = null;

			this.formColumns.forEach((item) => {
				if (item.is_required) {
					if (!has_required_but_empty) {
						if (!this.form[item.col] && typeof this.form[item.col] == "string") {
							has_required_but_empty = true;
							empty_item = item;
						}
					}
				}
			});

			// console.warn("遍历", this.formColumns);
			// console.warn("遍历", JSON.parse(JSON.stringify(this.formColumns)));

			//非空验证
			//0 &&
			if (has_required_but_empty) {
				let msg = "请完善" + empty_item.label + "信息";
				alertErr(msg);
				// let typeMap = {
				//   "": "填写",
				//   input: "填写",
				//   date: "选择",
				//   time: "选择",
				//   cascader: "选择",
				//   select: "选择",
				//   upload: "上传",
				//   "upload-file": "上传",
				//   "upload-image": "上传",
				// };
				return;
			}

			// return;

			let apiConfigItem = this.apiConfig[this.mode];
			let {
				//
				url,
				method,
				requestParams,
			} = apiConfigItem;
			let params = {
				...this.form,
				...this.otherSaveData,
			};

			//额外的请求参数  适用有默认值的场景  例如汽车品牌新增
			if (requestParams) {
				params = {
					...params,
					...requestParams,
				};
			}
			//例如  页面【新闻资讯列表】 设置 热搜新闻操作时
			if (this.customFormData) {
				params = {
					...params,
					...this.customFormData,
				};
			}

			for (var key in params) {
				if (typeof params[key] == "object") {
					params[key] = JSON.stringify(params[key]);
				}
			}

			//特殊处理货币
			this.formColumns.forEach((item) => {
				if (item.scene == "money") {
					//如果当前数据项目为货币类型 统一除以100
					if (+params[item.col]) {
						params[item.col] = params[item.col] * 100;
					}
				} else if (item.classType == 'String') {
					params[item.col] = String(params[item.col]) || ''
				} else if (item.classType == 'Number') {
					params[item.col] = Number(params[item.col]) || 0
				}
			});

			console.log("表单项提交 params", {
				...params
			});
			// return;
			// params.newsCover = "";
			this.isDisabled = true


			this.showLoading();

			this.$api({
				url: url,
				method: method,
				data: params,
				idInfo: {
					idKey: this.idKey,
					idVal: this.form[this.idKey],
				},
			}).then((res) => {
				this.hideLoading();

				setTimeout(() => {
					alertErr(res.msg)
				}, 200)

				if (res.code == 200) {
					this.show = false;
					this.$emit("eventCallback", {
						from: this.modalTitle,
						reflush: true,
					});
				}


				this.isDisabled = false
			});
		},

		// 图片上传
		//上传
		handle_upload_image_request(uploadInfo, formItem) {
			console.warn("handle_upload_image_request uploadInfo", uploadInfo);
			console.warn("handle_upload_image_request formItem", {
				...formItem
			});

			const formData = new FormData();
			let file = uploadInfo.file;
			formData.append("file", file);

			this.$apiUploadImage(formData).then((res) => {
				console.warn("图片上传res", res);
				let {
					type,
					saveFormat,
					col
				} = formItem;

				if (res && res.code == 200) {
					let url = res.data.url;

					if (type == "upload-image") {
						//图片上传
						if (saveFormat == "jsonObjectArray") {
							//多图上传
							let imageList = this.form[col];
							let item = {
								uid: file.uid,
								name: file.name,
								url: url
							};
							this.form[col] = [...imageList, item];
						} else if (saveFormat == "jsonStringArray") {
							let urlArr = this.form[col].split(",");
							urlArr.push(url);

							this.form[col] = urlArr.filter((v) => v).join(",");
						} else {
							this.form[col] = url;
						}
					}
				} else {
					// 测试使用
					let url =
						"http://travel.dx.hdapp.com.cn/statics/2023/12/19/1_20231219113117A024.jpg";
					if (saveFormat == "jsonObjectArray") {
						let imageList = this.form[col];
						let item = {
							name: file.name,
							url: url,
						};
						this.form[col] = [...imageList, item];
					} else if (saveFormat == "jsonStringArray") { } else {
						this.form[col] = url;
					}
				}

				// let name = res.data.name;
				// let path = res.data.path;

				//   console.log("富文本内容", this.content);
				//   const img = this.imgRoot + res.data;
				// success(img);
				// success(path);
			});
		},

		handle_upload_image_remove(option) {
			let {
				file,
				fileList,
				formItem
			} = option;
			console.warn("文件移除", file);
			console.warn("文件移除", fileList);
			console.warn("文件移除", {
				...formItem
			});

			let url = file.url;
			if (formItem.type == "upload-image") {
				//图片上传
				if (formItem.saveFormat == "jsonObjectArray") {
					//多图上传
					let imageList = this.form[formItem.col];
					// if (imageList) {
					//   try {
					//     imageList = JSON.parse(imageList);
					//   } catch (error) {
					//     imageList = [];
					//   }
					// }

					let index = imageList.findIndex((v) => v.uid == file.uid);
					if (index >= 0) {
						imageList.splice(index, 1);
					}

					this.form[formItem.col] = [...imageList];
				} else if (formItem.saveFormat == "jsonStringArray") {
					let imageUrlList = this.form[formItem.col].split(",").filter((v) => v);
					imageUrlList = imageUrlList.filter((v) => v != url);
					this.form[formItem.col] = imageUrlList.join();
				} else {
					// this.form[formItem.col] = url;
				}
			}

			console.warn('删除图片 this.form', {
				...this.form
			})
		},

		handle_upload_image_success(res, file) {
			console.warn("handle_upload_image_success");
			console.log("上传", res);
			// alert(res);
			if (res.code == 1) {
				// let image = res.image;
				// this.pingzheng_images.push(image);
			}
		},
		handle_upload_image_before(file) {
			console.warn("handle_upload_image_before");
			const isLt2M = file.size / 1024 / 1024 < 50; //文件大小
			return isLt2M;
		},

		// 视频上传
		//上传
		handle_upload_video_request(uploadInfo, formItem) {
			console.log('------------------------------');
			console.warn("handle_upload_video_request uploadInfo", uploadInfo);
			console.warn("handle_upload_video_request formItem", {
				...formItem
			});

			const formData = new FormData();
			let file = uploadInfo.file;
			formData.append("file", file);
			this.$apiUploadImage(formData).then((res) => {
				console.warn(" 视频上传res", res);
				if (res.code == 200) {
					let url = res.data.url;
					this.form[formItem.col] = url;
				}
			});
		},

		handle_upload_video_remove(option) {
			let {
				file,
				fileList,
				formItem
			} = option;
			console.warn("文件移除", file);
			console.warn("文件移除", fileList);
			console.warn("文件移除", {
				...formItem
			});

			let url = file.url;
			if (formItem.type == "upload-image") {
				//图片上传
				if (formItem.saveFormat == "jsonObjectArray") {
					//多图上传
					let imageList = this.form[formItem.col];
					// if (imageList) {
					//   try {
					//     imageList = JSON.parse(imageList);
					//   } catch (error) {
					//     imageList = [];
					//   }
					// }

					let index = imageList.findIndex((v) => v.url == url);
					if (index >= 0) {
						imageList.splice(index, 1);
					}

					this.form[formItem.col] = [...imageList];
				} else {
					// this.form[formItem.col] = url;
				}
			}
		},

		handle_upload_video_success(res, file) {
			console.warn("视频上传 handle_upload_video_success", res);
			if (res.code == 1) { }
		},
		handle_upload_video_before(file) {
			console.warn("handle_upload_video_before");
			const isLt2M = file.size / 1024 / 1024 < 1000; //文件大小
			return isLt2M;
		},


		//上传
		// 视频上传

		// 选项卡数据
		tabCardRowDelete(item, scope) {
			console.warn("表格行删除", {
				...item
			});
			console.warn("表格行删除", scope);
			// item.tabCardData.splice(scope.$index, 1);
		},
		tabCardAddItem(item) {
			let loopItem = JSON.parse(JSON.stringify(item.tabCardSingleItem));
			item.tabCardData.push(loopItem);
		},

		handlePictureCardPreview(file) {
			this.dialogImageUrl = file.url;
			this.dialogVisible = true;
		},

		// 标签列表
		tagClose(tag) {
			this.tagList.splice(this.tagList.indexOf(tag), 1);
		},
		tagShowInput() {
			this.tagInputVisible = true;

			setTimeout(() => {
				this.$nextTick(() => {
					// this.$refs["tagInputRef"].$refs.input.focus();
					this.$refs["tagInputRef"][0].$refs.input.focus();
				});
			}, 50);
		},
		tagInputConfirm() {
			let tagInputValue = this.tagInputValue.trim();
			if (tagInputValue) {
				if (this.tagList.includes(tagInputValue)) {
					alertErr("型号已存在！");
					// return
				} else {
					this.tagList.push(tagInputValue);
				}
			}
			this.tagInputVisible = false;
			this.tagInputValue = "";
		},
		// 标签列表

		// 分类节点选择
		treeNodeClick(obj, node, self, item) {
			console.warn("obj, item", obj, {
				...item
			});

			this.form[item.col] = obj.value;
			this.treeSelectTitle = obj.label;
			if (this.$route.name == "productCate") {
				this.form["level"] = obj.deep + 1;
			}

			this.$refs["popoverTree"][0].doClose();
			// console.warn("弹窗", );
		},
		// 分类节点选择

		testRichEditor() {
			let richItem = this.formColumns.find((v) => v.type == "rich-editor");
			let item = richItem;
			let vueComponent = this.$refs["tinyRichEditor-" + item.col][0];
			vueComponent.clear();
			console.warn("富文本内容", vueComponent);

			this.form[item.col] = "";
		},
	},
};
</script>

<style scoped lang="less">
/deep/ .upload-image .el-upload {
	width: 100px;
	height: 100px;
	line-height: 98px;
}

/deep/ .upload-video .el-upload {
	width: 100px;
	height: 100px;
	line-height: 98px;

	background-color: #fbfdff;
	border: 1px dashed #c0ccda;
	border-radius: 6px;
	box-sizing: border-box;
	cursor: pointer;
	vertical-align: top;
}

/deep/ .el-upload-list__item {
	background: #eef6ff !important;
	font-size: 16px;
}

.video-preview-box {
	margin-top: 20px;
}

/deep/ .modal-custom-base {
	margin-top: 50px !important;

	.el-dialog__header {
		.flex-between();
		border-bottom: 1px solid #eee;
		// background: #a98c4d;
		// background: #f7f7f7;
		// height: 50px;
		// line-height: 50px;
		// padding: 0 15px;
		// font-size: 14px;
		// color: #333;

		.el-dialog__title {
			color: #000;
		}

		.el-dialog__headerbtn {

			// top: 0;
			.el-dialog__close {
				color: #000;
				font-size: 20px;
				font-weight: bold;
			}
		}
	}

	.el-dialog__body {
		padding: 30px 40px;
		max-height: calc(100vh - 100px - 150px);
		overflow-y: auto;

		&::-webkit-scrollbar-thumb {
			border-radius: 5px;
			border: 8px solid #409eff;
			background: #fff;
		}

		&::-webkit-scrollbar {
			width: 8px;
			height: 0px;
		}
	}

	.el-dialog__footer {
		// text-align: center;
		border-top: 1px solid #eee;
	}
}

.modal-ctx {
	// padding: 30px 50px;
	// max-height: 60vh;
	// overflow-y: auto;
	// border-bottom: 1px solid #ddd;
}

// 处理表单样式
.input-items {
	.flex();
	flex-wrap: wrap;
	padding-bottom: 0px;

	.input-item {
		margin-bottom: 20px;
		width: 100%;
		// width: 50%;

		&.hidden-item {
			display: none;
		}

		&:last-child {
			margin-bottom: 0;
		}

		.input-box {
			width: 100%;
			display: flex;
			align-items: flex-start;

			.label {
				height: 32px;
				line-height: 32px;
				min-width: 160px;
				min-width: 100px;
				text-align: right;
				margin-right: 40px;
				font-size: 20px;
				font-size: 14px;
				font-family: PingFang SC;
				color: #666666;

				&.required {
					position: relative;

					&:after {
						content: "*";
						color: #f00;
						position: absolute;
						right: -15px;
						top: 3px;
						// font-weight: bold;
					}
				}
			}
		}

		//输入框组
		.inputs {
			.flex();

			.date-box {
				flex: 1;
			}

			.shuru-box {
				margin-left: 20px;
				flex: 4;
			}
		}

		.val {
			overflow: hidden;
			flex: 2;
			font-size: 20px;
			font-family: PingFang SC;
			color: #000000;

			&[data-type="treeSelect"] {
				overflow: visible;
			}

			.shuru {
				width: 100%;
				padding-left: 20px;
				outline: none;
				height: 40px;
				background: #ffffff;
				border: 1px solid #d4d8eb;
				border-radius: 4px;
				font-size: 16px;
			}

			.form-ele {
				.el-input {
					width: 100%;
				}

				.el-select {
					width: 100%;
				}

				.el-cascader {
					width: 100%;
				}
			}
		}
	}
}

// 页签
.tab-card-box {
	margin-top: 20px;

	.loop-add {
		margin-top: 20px;
		text-align: center;
	}
}

// 标签输入
.el-tag+.el-tag {
	margin-left: 10px;
}

.el-tag+.button-new-tag {
	margin-left: 10px;
}

.button-new-tag {
	height: 32px;
	line-height: 30px;
	padding-top: 0;
	padding-bottom: 0;
}

.input-new-tag {
	width: 120px !important;
	margin-left: 0;
	vertical-align: bottom;
}

.el-tag+.input-new-tag {
	margin-left: 15px;
}

// 标签输入

// 树形选择
.tree-box {
	position: relative;
}

// 树形选择</style>

<style lang="less">
.pop-tree {
	// position: absolute;
	z-index: 10;
	left: 0;
	right: 0;
	top: 32px;
	max-height: 300px;
	max-height: 400px;
	overflow-y: auto;
	// border: 1px solid #ccc;
	border-top: none;

	&::-webkit-scrollbar-thumb {
		border-radius: 3px;
		border: 5px solid #bbb;
		background: #fff;
	}

	&::-webkit-scrollbar {
		width: 5px;
		height: 0px;
	}
}
</style>